﻿using System.IO;
using SQLite;
using WarehouseManagementSystem.Entities;
using WarehouseManagementSystem.Services.IServices;

namespace WarehouseManagementSystem.Services;

public class SqliteService : ISqliteService
{
    public const string DbName = "db.sqlite3";

    public static readonly string DbPath =
        Path.Combine(
            Environment.CurrentDirectory, DbName);

    private SQLiteAsyncConnection? _connection;

    public SQLiteAsyncConnection Connection => _connection ??= new SQLiteAsyncConnection(DbPath);

    public bool IsInitialized => Connection.Table<Customer>().CountAsync().Result > 0;
    public async Task InitializeAsync()
    {
        await using var dbFileStream = new FileStream(DbPath, FileMode.OpenOrCreate);

        await using var dbAssetStream =
            typeof(SqliteService).Assembly.GetManifestResourceStream(DbName) ??
            throw new Exception($"Manifest not found: {DbName}");

        await dbAssetStream.CopyToAsync(dbFileStream);
    }

    public async Task CloseAsync() => await Connection.CloseAsync();
}